/**
 * @author Daniel
 *
 * Usage:
 * 	HTML:
 *	<div id="ddlist"></div>
 *  Javascript:
 *  $('#ddlist').iconDropdownList({
 *		className: 'iconDropdownList'
 *		, iconClassName: 'icon-base my-func-icon'
 *		, dropdownIndicatorClassName: 'icon-base small-triangle-icon'
 *		, menuData: {menu1:{display:'menu 1', clickFunc:function(){console.log('click menu1');}}, menu2:{display:'menu 2', clickFunc:function(){console.log('click menu2');}}}  //{menuName:{display:'', clickFunc:null}}; e.g. {sharePhoto:{display:'Share Photo', clickFunc:function(){}}}
 *	});
 */

(function($) {
	var iconDropdownList = {
		
		options: {
			className: ''
			, iconClassName: ''
			, dropdownIndicatorClassName: ''
			, menuData: null  //{menuName:{display:'', clickFunc:null}}; e.g. {sharePhoto:{display:'Share Photo', clickFunc:function(){}}}
			, clickHandler: null  //当设置了该方法，则点击执行该方法，不会出现下拉列表，
		}
		
		, _create: function() {
			var self = this;
			self._constructHtml();	
			self._bindEvents();					
		}
		
		, _constructHtml: function() {
			var self = this;
			var container = $(self.element[0]);
			
			container.addClass(self.options.className).html('<div class="normal"><div><span class="' + self.options.iconClassName + '"></span><span class="' + self.options.dropdownIndicatorClassName + '"></span></div><div class="list"><ul></ul></div></div>');
			var iconMenu = container.find('.normal');
			var dropdownListDiv = container.find('.list');
			var ulElem = dropdownListDiv.find('ul');
			
			if (self.options.menuData) {
				$.each(self.options.menuData, function(menuName, data) {
					var display = data['display'];
					var clickFunc = data['clickFunc'];
					var liElem = $('<li/>').text(display).bind('click', function(e){
						dropdownListDiv.hide();
						iconMenu.removeClass('dropdown');
						if (clickFunc) clickFunc();
						e.stopPropagation();
					});
					ulElem.append(liElem);
				});	
			}
			
			dropdownListDiv.hide();					
		}
		
		, _bindEvents: function() {
			var self = this;
			var container = $(self.element[0]);
			
			var iconMenu = container.find('.normal');
			var dropdownListDiv = container.find('.list');
			
			if (self.options.clickHandler || typeof(self.options.clickHandler) == 'function') {
				iconMenu.bind('click', self.options.clickHandler)	
			} else {
				iconMenu.bind('click', function(e){
					dropdownListDiv.show();
					iconMenu.addClass('dropdown');
					e.stopPropagation();
				});
				
				$(document).bind('click', function(){
					dropdownListDiv.hide();
					iconMenu.removeClass('dropdown');							
				});						
			}
		}
	};
	
	$.widget('ft.iconDropdownList', iconDropdownList);
})(jQuery);